﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MyCompany.MyProject.Common.HttpContextUser;
using MyCompany.MyProject.Model;
using Newtonsoft.Json;
using System.Text.Encodings.Web;

namespace MyCompany.MyProject.Extensions.Auth;

/// <summary>
/// 接口返回数据类型
/// </summary>
public class ApiResponseHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    private readonly IUser _user;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="options"></param>
    /// <param name="logger"></param>
    /// <param name="encoder"></param>
    /// <param name="clock"></param>
    /// <param name="user"></param>
    public ApiResponseHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock,IUser user) : base(options, logger, encoder, clock)
    {
        _user = user;
    }

    /// <summary>
    /// 授权认证的方法
    /// </summary>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 无权限 未登录
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
    {
        Response.ContentType = "application/json";
        Response.StatusCode = StatusCodes.Status401Unauthorized;
        await Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE401)).MessageModel));
    }

    /// <summary>
    /// 403 无权限
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
    {
        Response.ContentType= "application/json";
        if (_user.MessageModel != null)
        {
            Response.StatusCode = _user.MessageModel.status;
            await Response.WriteAsync(JsonConvert.SerializeObject(_user.MessageModel));
        }
        else
        {
            Response.StatusCode= StatusCodes.Status403Forbidden;
            await Response.WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE403).MessageModel));
        }
    }

}
